<template>
  <div class="p-4">
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-lg font-bold">拼车信息</h2>
        <el-button type="primary" @click="dialogVisible = true">发起拼车</el-button>
      </div>

      <el-table :data="carpools" border stripe>
        <el-table-column prop="carpool_id" label="ID" width="80" />
        <el-table-column prop="departure" label="出发地" />
        <el-table-column prop="destination" label="目的地" />
        <el-table-column prop="start_time" label="出发时间">
          <template #default="scope">
            {{ new Date(scope.row.start_time).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="seats_available" label="剩余座位" />
        <el-table-column prop="current_participants" label="当前参与" />
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" type="danger" @click="deleteCarpool(scope.row.carpool_id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发起拼车弹窗 -->
    <el-dialog v-model="dialogVisible" title="发起拼车" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="出发地" prop="departure">
          <el-input v-model="form.departure" />
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input v-model="form.destination" />
        </el-form-item>
        <el-form-item label="出发时间" prop="start_time">
          <el-date-picker
              v-model="form.start_time"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择出发时间"
          />
        </el-form-item>

        <el-form-item label="座位数" prop="seats_available">
          <el-input-number v-model="form.seats_available" :min="1" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {ElMessageBox} from 'element-plus'
import {useRouter} from 'vue-router'

const router = useRouter()
const BASE_URL = 'http://localhost:8080'

// ✅ 获取当前用户
const user = JSON.parse(localStorage.getItem('user'))
if (!user || !user.user_id) {
  ElMessage.error('用户未登录，请重新登录')
  // 跳转到登录页面
  router.push('/login')
}

// 拼车数据
const carpools = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)

// 表单数据（使用当前用户 ID）
const form = ref({
  initiator_id: user.user_id,
  departure: '',
  destination: '',
  seats_available: 1,
  start_time: ''
})

const rules = {
  departure: [{required: true, message: '请输入出发地', trigger: 'blur'}],
  destination: [{required: true, message: '请输入目的地', trigger: 'blur'}],
  seats_available: [{required: true, message: '请输入座位数', trigger: 'change'}],
  start_time: [{required: true, message: '请选择出发时间', trigger: 'change'}]
}

// 加载拼车数据
const loadData = async () => {
  try {
    const res = await axios.get(`${BASE_URL}/carpool/list`)
    if (res.data.state === 200) {
      carpools.value = res.data.data
    } else {
      ElMessage.error(res.data.message || '加载失败')
    }
  } catch (err) {
    ElMessage.error('请求失败')
  }
}

// 提交拼车信息
const submitForm = async () => {
  await formRef.value.validate()
  try {
    await axios.post(`${BASE_URL}/carpool/add`, form.value)
    ElMessage.success('发起成功')
    dialogVisible.value = false
    // ✅ 重置表单，保留用户 ID
    form.value = {
      initiator_id: user.user_id,
      departure: '',
      destination: '',
      seats_available: 1,
      start_time: ''
    }
    loadData()
  } catch (err) {
    ElMessage.error('提交失败')
  }
}

// 删除拼车信息
const deleteCarpool = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条拼车信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`${BASE_URL}/carpool/delete/${id}`)
    ElMessage.success('删除成功')
    loadData()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
</style>